package com.example.petadoption.Config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors(cors -> cors.configure(http)) // 启用默认CORS配置
                .csrf(csrf -> csrf.disable())       // 禁用CSRF（REST API无状态）
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers(
                                "/api/users/register",
                                "/v3/api-docs/**",
                                "/swagger-ui/**"
                        ).permitAll()                   // 开放注册和文档接口
                        .requestMatchers("/api/pets").hasRole("ADMIN") // 仅管理员可添加宠物
                        .anyRequest().authenticated()  // 其他接口需要登录
                )
                .httpBasic(basic -> {});           // 基础认证

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}